from collections import deque


def bfs(n, m, mp, x1, y1, x2, y2):
    # 四个方向，分别是下、上、右、左
    dx = [1, -1, 0, 0]
    dy = [0, 0, -1, 1]

    # 初始化距离数组，-1 表示未访问
    dis = [[-1] * (m + 1) for _ in range(n + 1)]

    # 如果起点或终点为障碍物，则无法到达
    if mp[x2][y2] == 0:
        return -1

    # BFS 队列
    q = deque([(x1, y1)])
    dis[x1][y1] = 0  # 起点的距离为 0

    while q:
        x, y = q.popleft()  # 取出队头
        for i in range(4):
            xx, yy = x + dx[i], y + dy[i]
            # 如果新的坐标合法且未访问且不是障碍物
            if 1 <= xx <= n and 1 <= yy <= m and mp[xx][yy] == 1 and dis[xx][yy] == -1:
                dis[xx][yy] = dis[x][y] + 1  # 更新距离
                q.append((xx, yy))  # 将新的坐标加入队列

    return dis[x2][y2]  # 返回到达终点的最短路径长度


def main():
    n, m = map(int, input().split())  # 输入地图的行列数
    mp = [[0] * (m + 1) for _ in range(n + 1)]  # 地图初始化
    for i in range(1, n + 1):
        row = list(map(int, input().split()))  # 输入地图的每一行
        for j in range(1, m + 1):
            mp[i][j] = row[j - 1]  # 将输入的值赋给地图数组

    # 输入起点和终点坐标
    x1, y1, x2, y2 = map(int, input().split())

    # 调用 BFS 求解最短路径
    result = bfs(n, m, mp, x1, y1, x2, y2)

    print(result)


if __name__ == "__main__":
    main()